package controller

import (
	"context"
	"detection-web/internal/dao"
	"detection-web/internal/service"
	"encoding/json"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
)

type cPromoteOrder struct{}

var PromoteOrder = cPromoteOrder{}

// GetShopAppIdsByStatus 根据状态获ID列表
func (c *cPromoteOrder) GetShopAppIdsByStatus(ctx context.Context, status int) ([]string, error) {
	if status <= 0 {
		return nil, gerror.NewCode(gcode.CodeInvalidParameter, "状态参数无效")
	}

	shopAppIds, err := service.PromoteOrder().GetShopAppIdsByStatus(ctx, status)
	if err != nil {
		return nil, gerror.Wrap(err, "获取ID失败")
	}

	return shopAppIds, nil
}

// CheckProductStatusConsole 商品状态检查
func (c *cPromoteOrder) CheckProductStatusConsole(r *ghttp.Request) {
	// 直接调用服务层检查商品状态
	response, err := service.PromoteOrder().CheckProductStatus(r.Context())
	if err != nil {
		// 返回错误响应
		r.Response.WriteJson(ghttp.DefaultHandlerResponse{
			Code:    500,
			Message: "检查商品状态失败: " + err.Error(),
		})
		return
	}

	// 同时打印到控制台和返回HTTP响应
	g.Log().Infof(r.Context(), "商品状态检查完成，结果: %+v", response)

	// 在控制台最后结束的时候打印出状态为2的共有多少条数据
	g.Log().Infof(r.Context(), "==========================================")
	g.Log().Infof(r.Context(), "状态为2的数据统计:")
	g.Log().Infof(r.Context(), "总记录数: %d", response.TotalCount)
	g.Log().Infof(r.Context(), "正常商品数: %d", response.NormalCount)
	g.Log().Infof(r.Context(), "异常商品数: %d", response.AbnormalCount)
	g.Log().Infof(r.Context(), "==========================================")

	// 返回成功响应
	r.Response.WriteJson(ghttp.DefaultHandlerResponse{
		Code:    200,
		Message: "success",
		Data:    response,
	})
}

// GetRawWechatAPIResponseHttp 获取微信API原始响应
func (c *cPromoteOrder) GetRawWechatAPIResponseHttp(r *ghttp.Request) {
	// 从POST请求体获取参数
	var reqBody struct {
		UserNames []string `json:"userNames"`
	}

	bodyBytes := r.GetBody()
	if len(bodyBytes) > 0 {
		// 如果有请求体，尝试解析
		if err := json.Unmarshal(bodyBytes, &reqBody); err != nil {
			r.Response.WriteJson(ghttp.DefaultHandlerResponse{
				Code:    400,
				Message: "解析请求体失败: " + err.Error(),
			})
			return
		}
	}

	userNames := reqBody.UserNames
	if len(userNames) == 0 {
		orderData, err := service.PromoteOrder().GetOrderDataByStatus(r.Context(), 2)
		if err != nil {
			r.Response.WriteJson(ghttp.DefaultHandlerResponse{
				Code:    500,
				Message: "获取status=2的订单数据失败: " + err.Error(),
			})
			return
		}

		if len(orderData) == 0 {
			r.Response.WriteJson(ghttp.DefaultHandlerResponse{
				Code:    400,
				Message: "没有状态为2的订单数据进行检查",
			})
			return
		}

		// 提取所有promotion_id
		var promotionIds []string
		for _, order := range orderData {
			if order.PromotionId != "" {
				promotionIds = append(promotionIds, order.PromotionId)
			}
		}

		materials, err := dao.PromoteOrderMaterial.Ctx(r.Context()).
			Fields("user_name").
			WhereIn("promotion_id", promotionIds).
			Group("user_name").
			All()

		if err != nil {
			r.Response.WriteJson(ghttp.DefaultHandlerResponse{
				Code:    500,
				Message: "查询promote_order_material表失败: " + err.Error(),
			})
			return
		}

		// 提取user_name列表
		for _, material := range materials {
			userName := material["user_name"].String()
			if userName != "" {
				userNames = append(userNames, userName)
			}
		}

		g.Log().Infof(r.Context(), "从数据库获取到 %d 个user_name", len(userNames))

		//// 限制为前20条进行测试
		//if len(userNames) > 20 {
		//	userNames = userNames[:20]
		//	g.Log().Infof(r.Context(), "测试模式：限制处理前20条数据")
		//}
	}

	// 调用并发API获取微信数据
	results, err := service.HttpClient().CallWechatAPIConcurrent(r.Context(), userNames)
	if err != nil {
		r.Response.WriteJson(ghttp.DefaultHandlerResponse{
			Code:    500,
			Message: "调用微信API失败: " + err.Error(),
		})
		return
	}

	// 解析每个用户的API响应
	var rawResponses []map[string]interface{}
	for username, data := range results {
		// 尝试解析JSON响应
		var apiResp map[string]interface{}
		if err := json.Unmarshal(data, &apiResp); err != nil {
			// 如果解析失败，返回原始字符串
			rawResponses = append(rawResponses, map[string]interface{}{
				"username":    username,
				"raw_data":    string(data),
				"parse_error": err.Error(),
			})
		} else {
			// 解析成功，添加用户名信息
			apiResp["username"] = username
			rawResponses = append(rawResponses, apiResp)
		}
	}

	// 返回原始响应结果
	r.Response.WriteJson(ghttp.DefaultHandlerResponse{
		Code:    200,
		Message: "success",
		Data: map[string]interface{}{
			"total_users":   len(userNames),
			"success_users": len(results),
			"raw_responses": rawResponses,
			"request_users": userNames,
		},
	})
}
